package com.luo.gmall.auth.service.impl;

import com.luo.gmall.auth.feign.GmallUmsClient;
import com.luo.gmall.auth.config.JwtProperties;
import com.luo.gmall.auth.exception.AuthException;
import com.luo.gmall.auth.service.AuthService;
import com.luo.gmall.common.utils.CookieUtils;
import com.luo.gmall.common.utils.IpUtil;
import com.luo.gmall.common.utils.JwtUtils;
import com.luo.gmall.ums.entity.UserEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Zoro
 * @date 2021年11月20
 */
@Service
@RequiredArgsConstructor
@EnableConfigurationProperties(JwtProperties.class)
public class AuthServiceImpl implements AuthService {

    private final GmallUmsClient gmallUmsClient;

    private final JwtProperties jwtProperties;

    @Override
    public void login(String loginName, String password, HttpServletRequest request, HttpServletResponse response) {

        // 1. 完成远程请求，获取用户信息
        UserEntity userEntity = gmallUmsClient.queryUser(loginName, password).getData();

        // 2. 判断用户信息是否为空
        if (userEntity == null) {
            throw new AuthException("账户或密码错误!");
        }

        // 3. 把用户id及用户名放入载荷
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userEntity.getId());
        map.put("username", userEntity.getUsername());

        // 4. 为了防止jwt被别人盗取，载荷中加入用户ip地址
        String ipAddress = IpUtil.getIpAddressAtService(request);
        map.put("ip", ipAddress);

        try {
            // 5. 制作jwt类型的token信息
            String token = JwtUtils.generateToken(map,
                    jwtProperties.getPrivateKey(),
                    jwtProperties.getExpire() * 60);

            // 6. 把jwt放入cookie中
            CookieUtils.setCookie(request,
                    response,
                    jwtProperties.getCookieName(),
                    token,
                    jwtProperties.getExpire() * 60);
            // 7.用户昵称放入cookie中，方便页面展示昵称
            CookieUtils.setCookie(request,
                    response,
                    jwtProperties.getUnick(),
                    userEntity.getUsername(),
                    jwtProperties.getExpire() * 60);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AuthException("用户名或密码错误！");
        }
    }
}
